namespace TSL.Utility.Json
{
    using System;
    using System.Security;
    using System.Text;

    public class ExceptionConverter : IJavaScriptConverter
    {
        public ExceptionConverter()
        {
            base.m_AllowInheritance = true;
            base.m_serializableTypes = new Type[] { typeof(Exception), typeof(NotImplementedException), typeof(NotSupportedException), typeof(NullReferenceException), typeof(SecurityException) };
        }

        public override string Serialize(object o)
        {
            StringBuilder sb = new StringBuilder();
            this.Serialize(o, sb);
            return sb.ToString();
        }

        public override void Serialize(object o, StringBuilder sb)
        {
            Exception exception = (Exception) o;
            sb.Append("{\"Message\":");
            JavaScriptUtil.QuoteString(exception.Message, sb);
            sb.Append(",\"Type\":");
            JavaScriptUtil.QuoteString(o.GetType().FullName, sb);
            sb.Append("}");
        }

        public override bool TrySerializeValue(object o, Type t, StringBuilder sb)
        {
            Exception exception = o as Exception;
            if (exception != null)
            {
                this.Serialize(exception, sb);
                return true;
            }
            return base.TrySerializeValue(o, t, sb);
        }
    }
}

